package com.lambkit.module.cms.web.directive;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.module.cms.rpc.model.CmsArticle;
import com.lambkit.module.cms.rpc.model.CmsComment;
import com.lambkit.web.LambkitControllerContext;
import com.lambkit.web.directive.LambkitDirective;
import com.lambkit.web.directive.LambkitPaginateDirective;
import com.lambkit.web.directive.annotation.JFinalDirective;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Henry Yang 杨勇 (gismail@foxmail.com)
 * @version 1.0
 * @Package com.lambkit.module.cms.web.directive
 */
@JFinalDirective("commentPage")
public class CommentPageDirective extends LambkitDirective {

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {

        Controller controller = LambkitControllerContext.get();

        int page = controller.getParaToInt(1, 1);
        int pageSize = getParaToInt("pageSize", scope, 10);

        CmsArticle article = controller.getAttr("article");

        Page<CmsComment> articlePage = CmsComment.service().paginateByArticleIdInNormal(page, pageSize, article.getArticleId());
        scope.setGlobal("commentPage", articlePage);
        renderBody(env, scope, writer);
    }


    @Override
    public boolean hasEnd() {
        return true;
    }


    @JFinalDirective("commentPaginate")
    public static class TemplatePaginateDirective extends LambkitPaginateDirective {

        @Override
        protected String getUrl(int pageNumber) {
            HttpServletRequest request = LambkitControllerContext.get().getRequest();
            String url = DirectveKit.replacePageNumber(request.getRequestURI(), pageNumber);
            return StrKit.isBlank(getAnchor()) ? url : url + "#" + getAnchor();
        }

        /**
         * 未完成
         * @return
         */
        private String getAnchor() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
        protected Page<?> getPage(Env env, Scope scope, Writer writer) {
            return (Page<?>) scope.get("commentPage");
        }

    }
}
